import {
  LockOutlined,
  UserOutlined,
  BulbTwoTone,
  MailOutlined,
  FolderOutlined,
} from '@ant-design/icons';
import { Alert, Tabs, message } from 'antd';
import React, { useState } from 'react';
import ProForm, { ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { useIntl, connect, FormattedMessage } from 'umi';
import type { Dispatch } from 'umi';
import type { StateType } from '@/models/login';
import type { LoginParamsType } from '@/services/login';
import type { ConnectState } from '@/models/connect';
import request from '@/utils/request';

import styles from './index.less';

export type LoginProps = {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status, type: loginType } = userLogin;
  const [type, setType] = useState<string>('account');
  const intl = useIntl();

  const handleSubmit = (values: LoginParamsType) => {
    if (type === 'account') {
      const { dispatch } = props;
      dispatch({
        type: 'login/login',
        payload: { ...values, type },
      });
    } else {
      console.log(values);
      request('/api/services/app/TenantAndUser/Register', {
        method: 'POST',
        data: values,
      }).then((response) => {
        if (response && response.success) {
          message.success('恭喜，注册成功!现在可以登录啦。');
        } else {
          message.error(response.error.message);
        }
      });
    }
  };
  return (
    <div className={styles.main}>
      <ProForm
        initialValues={{
          autoLogin: true,
          tenant: 'Default',
        }}
        isKeyPressSubmit={true}
        submitter={{
          render: (_, dom) => dom.pop(),
          submitButtonProps: {
            loading: submitting,
            size: 'large',
            style: {
              width: '100%',
            },
          },
        }}
        onFinish={(values) => {
          handleSubmit(values as LoginParamsType);
          return Promise.resolve();
        }}
      >
        <Tabs activeKey={type} onChange={setType}>
          <Tabs.TabPane
            key="account"
            tab={intl.formatMessage({
              id: 'pages.login.accountLogin.tab',
              defaultMessage: 'Account password login',
            })}
          />
          <Tabs.TabPane
            key="regist"
            tab={intl.formatMessage({
              id: 'pages.login.accountRegist.tab',
              defaultMessage: 'Account regist',
            })}
          />
        </Tabs>

        {status === 500 && !submitting && loginType == 'account' && (
          <LoginMessage
            content={intl.formatMessage({
              id: 'pages.login.accountLogin.errorMessage',
              defaultMessage: 'Incorrect account or password',
            })}
          />
        )}
        {type === 'account' && (
          <>
            <ProFormText
              name="tenant"
              placeholder="账套: Default"
              fieldProps={{
                size: 'large',
                prefix: <BulbTwoTone className={styles.prefixIcon} />,
              }}
            />
            <ProFormText
              name="userNameOrEmailAddress"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.username.placeholder',
                defaultMessage: 'Username: admin or user',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.username.required"
                      defaultMessage="Please enter user name!"
                    />
                  ),
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.password.placeholder',
                defaultMessage: 'Password: 123456',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="Please enter password!"
                    />
                  ),
                },
              ]}
            />
            <div
              style={{
                marginBottom: 24,
              }}
            >
              <ProFormCheckbox noStyle name="autoLogin">
                <FormattedMessage id="pages.login.rememberMe" defaultMessage="Auto login" />
              </ProFormCheckbox>
            </div>
          </>
        )}

        {type === 'regist' && (
          <>
            <Alert
              message="提示：账套注册完默认超级管理员为admin"
              type="warning"
              closable
              style={{ marginBottom: 16 }}
            />
            <ProFormText
              name="tenancyName"
              placeholder="账套名"
              fieldProps={{
                size: 'large',
                prefix: <BulbTwoTone className={styles.prefixIcon} />,
              }}
              rules={[
                {
                  required: true,
                  message: '请输入账套名',
                },
              ]}
            />
            <ProFormText
              name="name"
              placeholder="账套别名"
              fieldProps={{
                size: 'large',
                prefix: <BulbTwoTone className={styles.prefixIcon} />,
              }}
              rules={[
                {
                  required: true,
                  message: '请输入账套别名',
                },
              ]}
            />
            <ProFormText
              name="adminEmailAddress"
              placeholder="电子邮件"
              fieldProps={{
                size: 'large',
                prefix: <MailOutlined className={styles.prefixIcon} />,
              }}
              rules={[
                {
                  required: true,
                  message: '请输入电子邮件',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder="请输入密码"
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.password.required"
                      defaultMessage="Please enter password！"
                    />
                  ),
                },
              ]}
            />
            <ProFormText
              name="company"
              placeholder="公司名称"
              fieldProps={{
                size: 'large',
                prefix: <FolderOutlined className={styles.prefixIcon} />,
              }}
              rules={[
                {
                  required: true,
                  message: '公司名称必填',
                },
              ]}
            />
          </>
        )}
      </ProForm>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
